var MailRead = Class.create();
MailRead.prototype = {
	initialize: function() {
		this.init();
	},
	init: function() {
		// 当前页面列表的一个临时缓存，通过这个缓存获取信件的上一封、下一封
		this.cacheList = [];
		// 当前页号(记录当前是从列表页面的哪一页进来读信的，这个页数编号的起始点从1开始)
		this.page = 1;
		// 当前的文件夹ID（目前还没用）
		this.folder = 1;
		// 上一封邮件ID，下一封邮件ID
		this._prev_page = 0;
		this._next_page = 1;
		// 当前页面的邮件列表数
		this.page_count = 0;
		// 当前读信页面的的数据缓存
		this.currentMail = {};
		// 读过的邮件做一个缓存
		this.readMailCache = {};
		// 快速回复的常用语
		this.replayOptions = ['请选择常用回复语','收到，谢谢！','收到，我会尽快处理！','好的，马上办理！'];
		// 在未读邮件中已经被读过，或者被删除的邮件
		this.delMail = null;
        // 存放 Disposition to
        this.disposition_to = null;
		// 移动、删除邮件的操作提示
		this.op_tips = {
			'fid_0': '邮件操作成功！',        // 移动邮件夹
			'fid_-1': '邮件已经被永久删除！', // 永久删除邮件
			'fid_4': '邮件已经被删除！',      // 删除邮件
			'fid_1': '邮件已经不是垃圾邮件！',// 非垃圾邮件操作
			'fid_3': '邮件已经被垃圾举报！'   // 垃圾邮件举报操作
		};
	},
    initEvent: function() {
		var self = this;
        var _tmp_dl = [{
            name: 's_rt',
            exec: function(){
				self.rtListPage();
            }
        }, {
            name: 's_prev',
            exec: function(){
                self.getMailRead(PREV_ID);
            }
        }, {
            name: 's_next',
            exec: function(){
                self.getMailRead(NEXT_ID);
            }
        }];
		
		var _tmp_dl_clk = [
			{
            name: 's_rp',
            exec: function(){
                self.replyMail('reply');
            }
        }, {
			name: 's_rpall',
			exec: function() {
				self.replyMail('replyall');
			}
		}, {
            name: 's_fw',
            exec: function(){
                self.replyMail('forward');
            }
        }, {
            name: 's_delete',
            exec: function(){
                self.mailMove(-1);
            }
        }, {
            name: 's_delt',
            exec: function(){
                self.mailMove(4);
            }
        }, {
            name: 's_spam',
            exec: function(){
                self.mailMove(-1, 3);
				jsoplog.ucCapture('spammail');
            }
        }, {
            name: 's_unspam',
            exec: function(){
                self.mailMove(1)
            }
        }, {
            name: 's_print',
            exec: function(){
                self.mailPrint();
            }
        }, {
            name: 's_source',
            exec: function(){
                self.viewMailSource();
            }
        }, {
            name: 's_download',
            exec: function(){
                self.downloadMailSource();
            }
        }, {
			name: 's_move',
			exec: function(EL, event) {
				var l = self.getFolderList();
				if(l.length == 0) {
					Tips.show('没有可移至的文件夹', 3);
					return false;
				}
                menu.showMenu(EL, DOM.sohuMailMain, l, 'menu', true, null, event);  
			}
		}, {
            name: 's_reply_area',
            exec: function(){
                self.isFastReply();
            }
        }, {
            name: 's_reply_button',
            exec: function(){
                self.replyMail('fastreply');
            }
        }, {
            name: 's_saveaddr',
            exec: function(EL, event){
                self.saveAddr(EL, event);
            }
        }, {
            name: 's_refuse',
            exec: function(EL){
                self.refuseAddr(EL);
            }
        }, {
            name: 's_savealladdr',
            exec: function(EL, event){
                self.saveAllAddr(EL, event);
            }
        }, {
            name: 's_filepreview',
            exec: function(){
                self.focusPreview();
            }
        }, {
            name: 's_ispreview',
            exec: function(EL){
                self.isPreview(EL);
            }
        }, {
			name: 's_star',
			exec: function(EL) {
				self.setStar(EL);
			}
		}, {
			name: 'reply_notifier',
			exec: function(EL) {
				self.reply_notifier(EL, 1);
			}
		}, {
			name: 'cancel_reply_notifier',
			exec: function(EL) {
				self.reply_notifier(EL, 0);
            }
        }, {
			name: 'edm_activity',
			exec: function(EL) {
				var exec_event = EL.getAttribute('eventname');
				if(!exec_event || exec_event == '') return false;
				try {
					return new Function('return ' + exec_event)();
				} catch(e) {}
			}
		}];
		
		var _gpcn = Element.getParentNodeByClassName, _gpatr = Element.getParentNodeByAttribute;
		DOM.readMail.observe('click', function(event) {
			if(isConferenceMode) return false;
			try {
				if (mailSearch && mailSearch.searchReadPanel) return false;
			} catch(e) {}
			var el = event.target;
			_tmp_dl.each(function(item) {
				var e = _gpcn(el, item.name);
				if (e) Event.stop(event);
				return false;
			});
			_tmp_dl_clk.each(function(item) {
				if(item.cevt) {
					var _flag = false;
					item.cevt.each(function(_item) {
						if(_gpcn(el, _item)) _flag = true;
					});
					if(_flag) return false;
				}
				var e = _gpcn(el, item.name);
				if (e) {
					item.exec(e, event);
					Event.stop(event);
				}
				return false;
			});
		}).observe('mouseover', function(event) {
			if(isConferenceMode) return false;
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-hover');
		}).observe('mouseout', function(event) {
			if(isConferenceMode) return false;
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-hover');
		}).observe('mousedown', function(event) {
			if(isConferenceMode) return false;
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-press');
			if(!Event.isLeftClick(event)) return false;
			(function() {
				try {
					if (mailSearch && mailSearch.searchReadPanel) return false;
				} catch(e) {}
				_tmp_dl.each(function(item) {
					if(item.cevt) {
						var _flag = false;
						item.cevt.each(function(_item) {
							if(_gpcn(el, _item)) _flag = true;
						});
						if(_flag) return false;
					}
					var e = _gpcn(el, item.name);
					if(e) {
						eventStop(event);
						item.exec(e, event);
						return false;
					}
				});
			})();
		}.bind(this)).observe('mouseup', function(event) {
			if(isConferenceMode) return false;
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-press');
		});
    },
	// 读信时，返回到当前信件所在的列表页面
	rtListPage: function() {
		try {
			// 返回按钮定位到信件所在的当前列表页面
			var _id = this.currentMail.rowid, _index = 0, _flag = false;
			this.cacheList.each(function(item, index) {
				if (item.rowid == _id && !_flag) {
					_index = index-1;
					_flag = true;
				}
			});
			var _pp = typeof this._prev_page != 'number' ? -1 : this._prev_page;
			var _page = _pp + 1 + parseInt(_index/PAGE_CAPACITY);
			/*
			if(this._next_page > mailList.currentPage) {
				_page = mailList.currentPage + parseInt(_index/PAGE_CAPACITY);
			} else {
				_page = mailList.currentPage - parseInt(_index/PAGE_CAPACITY);
			}
			*/
			mailList.getMailPage(mailList.currentFolder, _page);
		} catch(e) {}
	},
	getMailRead: function(id, is_rsh) {
		if(!id) return;
		var _params = {
			id: id
		};
		if(this.folder == 2) {
			writemail.draft2Write(_params);
			return false;
		}
		this.currentCid = id;
		var _get_ = function() {
			var _sf = arguments.callee;
			var _ed = arguments[0];
			this.cacheList.each(function(item, index) {
				if(item.rowid == id) {
					if(this.cacheList[index+1]) {
						NEXT_ID = this.cacheList[index+1].rowid;
					} else {
						NEXT_ID = null;
						if (this.cacheList.length >= (PAGE_CAPACITY - 1) && !_ed) {
							var params = {
								folder_id: this.folder,
								start: this._next_page * PAGE_CAPACITY,
								length: PAGE_CAPACITY
							};
							folder_list(params, function(ret){
								if (Object.isArray(ret)) {
									this.cacheList = this.cacheList.concat(ret);
									if(ret.length == 0) {
										_sf.apply(this, [true]);
									} else {
										this._next_page++;
										_sf.apply(this);
									}
								}
							}.bind(this));
							return false;
						}
					}
					if(this.cacheList[index-1]) {
						PREV_ID = this.cacheList[index-1].rowid;
					} else {
						PREV_ID = null;
						if (this._prev_page != null && this._prev_page >= 0) {
							var params = {
								folder_id: this.folder,
								start: this._prev_page * PAGE_CAPACITY,
								length: PAGE_CAPACITY
							};
							folder_list(params, function(ret){
								if (ret.length != 0) {
									this.cacheList = ret.concat(this.cacheList);
									this._prev_page--;
									_sf.apply(this);
								}
							}.bind(this));
							return false;
						}
					}
					if(this.folder == -2) this.cacheList = this.delCinList(index, this.cacheList);
					if (this.readMailCache['mail_' + id]) {
						this.getMailReadCallback(is_rsh, this.readMailCache['mail_' + id]);
						// mail_read(_params, this.getMailReadCallback.bind(this, is_rsh));
					} else {
						mail_read(_params, this.getMailReadCallback.bind(this, is_rsh));
					}
				}
			}.bind(this));
		}.bind(this);
		_get_();
	},
	
	// 设置当前邮件未读，并且同步缓存数据
	setCurrentMailRead: function() {
		if(arguments.length == 0) return;
		var data = arguments[0];
		if(typeof data != 'object') return;
		if(data.have_read) return false;
		try {
			mailList.changeFolderListUnread(data.folder, true);
		} catch(e) {}
		try {
			mailList.refreshFolderListNewMail();
		} catch(e) {}
		try {
			var p = {
				id: data.rowid,
				method: 0
			};
			mail_move(p);
			var _mail_item = $('tr_' + id);
			if (_mail_item)	_mail_item.removeClassName('noread');
		} catch(e) {}
	},
	
	getMailReadCallback: function(is_rsh, ret) {
		if (typeof ret != 'object') {
			_dialog.alert({info: '系统错误，请重试！'});
			return false;
		}
		if(!this.readMailCache['mail_' + ret.rowid]) this.readMailCache['mail_' + ret.rowid] = ret;
		this.currentMail = ret;
		hiddenAllPanel();
		DOM.readMail.show();
		// 读信列表的优化：将未读邮件箱、收件箱、垃圾邮件箱中的未读邮件数目放在前端的列表中来维护 FolderList
		this.setCurrentMailRead(ret);
		this.showMailRead(ret);
		var _title = ret.envelope.subject.unescapeHTML().strip() == "" ? "无标题" : ret.envelope.subject.unescapeHTML();
		if (mailList.currentFolder != -2) {
			addAjaxHistory('readMail_' + ret.rowid, 'mailRead.getMailRead('+ ret.rowid +', true)', _title, is_rsh);
		}
		try {
			deleteLoadPage();
		} catch(e) { }
		try {
			// log记录
			jsoplog.sendPV('readmail');
		} catch(e) {}
	},
	// 生成读信界面
	showMailRead: function(ret, light) {
		var _rmb1 = $('read_mail_bar1'), _rc = $('dialog_read'), _rmb2 = $('read_mail_bar2');
			if (!_rmb1 && !_rc && !_rmb2) {
				var c = new Template(mailReadTemplate).evaluate({
					read_width: 'width:' + (getRightPanelWidth() - staticValue.rightAdsWidth - getMainSpaceWidth() - 1) + 'px;',
					read_style: 'read',
					read_isads: (staticValue.rightAdsWidth == 0 ? 'display:none;' : ''),
					read_ads1: (staticValue.rightAdsWidth == 0 ? '' : readright1),
					read_ads2: (staticValue.rightAdsWidth == 0 ? '' : readright2)
				});
				DOM.readMail.innerHTML = c;
				_rmb1 = $('read_mail_bar1'), _rc = $('dialog_read'), _rmb2 = $('read_mail_bar2');
			} else {
				_rc.className = 'read';
			}
			_rc.innerHTML = this.createMail(ret, light);
			
			var _op = [], _opb = [], _opr = [], mc = mailConference, _f = this.currentFolder;
			_op.push('<div class="l-area rd">');
			_op.push(mc.createRtEL());
			_op.push(mc.createReplyEL(true));
			_op.push(mc.createReplyAllEL());
			_op.push(mc.createForwardEL());
			_op.push(mc.createSprEL());
			_op.push(mc.createDeleteEL());
			if (_f != 4 && _f != 5) _op.push(mc.createDelEL());
			_opb = [].concat(_op);
			if(_f != 4 && _f != 5 && !getSysAccount(ret.envelope.from[0][1])) _op.push(mc.createSpamEL());
			if(_f == 5) _op.push(mc.createUnspamEL());
			_op.push(mc.createSprEL());
			if (_f != 3) _op.push(mc.createMoveEL());
			_op.push('</div>');
			_opb.push(mc.createSprEL());
			_opb.push(mc.createPtEL());
			_opb.push(mc.createScEL('download/' + ret.mid + '.0'));
			_opb.push(mc.createDldEL('download/' + ret.mid + '.1'));
			_opb.push('</div>');
			
			_opr.push('<div class="r-area">');
			if(!PREV_ID && !NEXT_ID) {
				_opr.push(mc.createPrevEL(true));
				_opr.push(mc.createNextEL(true));
			} else if(!PREV_ID) {
				_opr.push(mc.createPrevEL(true));
				_opr.push(mc.createNextEL());
			} else if(!NEXT_ID) {
				_opr.push(mc.createPrevEL());
				_opr.push(mc.createNextEL(true));
			} else {
				_opr.push(mc.createPrevEL());
				_opr.push(mc.createNextEL());
			}
			_opr.push('</div>');
			_op = _op.concat(_opr);
			_opb = _opb.concat(_opr);
			_rmb1.innerHTML = _op.join('');
			_rmb2.innerHTML = _opb.join('');
			
		mailList.setReadMailCache(ret.rowid);
		//设置快捷回复选择常用语
		try {
			this.loadReplyText();
		} catch(e) {}
		
		// 设置自动回复
		try {
			this.loadSelectXfrom();
		} catch(e) {}
		
		// 自动滚动至顶部
		try {
			DOM.sohuMailMain.scrollTop = 0;
		} catch(e) {}
		// 读信页面面右侧的广告，没有广告的话就cache掉
		try {
			rightAdsPoll('right_ads1', 'right_ads2');
		} catch(e) {}
		try {
			changePanel('readMail', mailList.currentFolder);
		} catch(e) {}
		try {
			mail_send_e.init(['compose.wto'], 6, UID + genKeyCode());
		} catch (e) {}
	},
	
	// 创建单封信件显示的内容界面
	// light: string || array; 如果是搜索结果，高亮显示
    createMail: function(mail, light) {
        var mail_subj = (mail.envelope.subject.strip() == '') ? "无标题" : mail.envelope.subject;
		mail_subj = mail_subj.stripTags();
        var _from = mail.envelope.from[0];
        if (!_from) _from = ['', ''];
        var addrName = _from[1], myemail = UserSohuID, copyName = '', ccs = '', receiverName = '', recs = [], noInaddr = 0, receiverList = [];
        if (mail.envelope.to && mail.envelope.to.length > 0) {
            mail.envelope.to.each(function(s) {
                if (UserSohuID != s[1] && s[1] != '') {
                    receiverName += s[1] + ',';
                }
                // 在 已发送 中，将收件人的拒收、添加到地址薄屏蔽
                recs.push("<span title='" + s[1] + "'>" + getSenderName(s) + "</span>");
                if (s[1] != UserSohuID) {
                    if (!mailIsContact(s[1])) {
                        noInaddr++;
                    }
					if(!mailIsReceive(s[1], receiverList)) {
						receiverList.push(s);
					}
                }
            }.bind(this));
        }
        if (mail.envelope.cc && mail.envelope.cc.length > 0) {
            mail.envelope.cc.each(function(s){
                if (UserSohuID != s[1] && s[1] != '') {
                    copyName += s[1] + ',';
                }
                ccs += ("<span title='" + s[1] + "'>" + getSenderName(s) + "</span>, &nbsp;");
                if (s[1] != UserSohuID) {
                    if (!mailIsContact(s[1])) {
                        noInaddr++;
                    }
					if(!mailIsReceive(s[1], receiverList)) {
						receiverList.push(s);
					}
                }
            }.bind(this));
        }
		recs = recs.join('').strip();
		var _content = mail.display;
		
        var senderName = getSenderName(formatSysAccount(_from));
		
		var s_c = [senderName, mail_subj, _content];
		
		if(light && Object.isArray(light)) {
			s_c = mailSearch.replaceHeighLight(s_c, light);
		}
		var mx = mail.maximum;
		if(mx && mx != '') {
			s_c[2] = '<iframe id="maximum_'+ mail.rowid +'" onload="resizeMailContent(\'maximum_'+ mail.rowid +'\');" src="./download/'+ mx +'.7" style="width:100%;height:800px;border:0px" frameborder=0></iframe>';
		}
		
        var pageContent = [];
        pageContent.push('<dl id="read_title_content" style="width:100%;">');
        pageContent.push('<dt>');
        pageContent.push('<span title="'+ mailList.multiStar.title[mail.star] +'" sid="'+ mail.star +'" class="am s_star '+ mailList.multiStar.star[mail.star] +'" style="cursor:pointer;float:left;"></span> &nbsp;');
        
		pageContent.push('<a hidefocus="true">' + s_c[1] + '</a>');
        pageContent.push('</dt>');
        pageContent.push('<dd>发件人：<font style="size:12px" title="' + addrName + '">' + s_c[0] + '</font>');
        
        if (this.folder != 3) {
            // 发件人是否在地址薄里面
            if (!mailIsContact(addrName)) {
                pageContent.push('<a id="rd_add_contact" href="javascript:;" hidefocus="true" class="s_saveaddr" style="margin-left:15px;">保存到地址簿</a>');
            }
            // 发件人信箱是否被拒
            if (!mailIsBlack(addrName)) {
                pageContent.push('<a id="refuse.current.sender" hidefocus="true" href="javascript:;" class="s_refuse" style="margin-left:15px;">拒收</a>');
            }
        }
        pageContent.push('</dd>');
        var is_single = 0;
        // 是否显示回执提醒 1 是，0 不是
        var is_disp_notifier = 0;
        // 是否已经回复过了?? 1是 0 不是
        var is_disp_notifier_s = 0;
        mail.envelope.userhdrs.each(function(v){
        	try{
        		if(v[0] == "X-Sohu-SingleSent" && v[1] == "1"){
            		is_single = 1;
            	}
                if(v[0] == "Disposition-Notification-To"){
                    is_disp_notifier = 1;
                    this.disposition_to = v[1];
                }
                if(v[0] == "Disposition-Notification-Sent"){
                    is_disp_notifier_s = 1;
                }
        	} catch(e){}
       	}.bind(this));
        if (recs != '') {
            pageContent.push('<dd>');
            if(is_single == 0){
                pageContent.push('收件人：<font style="size:12px">' + recs + '</font>');
            } else{
                pageContent.push('分送给：<font style="size:12px">' + recs + '</font>');
            }
            if (noInaddr > 0) {
                pageContent.push('<a id="rd_add_contact_multi" href="javascript:;" class="s_savealladdr" style="margin-left:15px;" hidefocus="true">保存所有收件人</a>');
            }
            pageContent.push('</dd>');
        }
        
        pageContent.push('<dd>时　间：<font style="size:12px">');
        pageContent.push(strfTime(mail.envelope.date_sent * 1000) + '</font></dd>');
        if (ccs != '') {
            pageContent.push('<dd>抄　送：<font style="size:12px">' + ccs);
            pageContent.push('</font></dd>');
        }
        
        var attrfiles = [];
        var singleimage = [];
        var _attach = (mailList.currentFolder == 2) ? mail.envelope.attach : mail.attach;
		_attach = _attach ? _attach : [];
        var html_savetoudisk = "";
        try {
            if (_attach && _attach.length > 0) {
				var new_attach = [];
				_attach.each(function(item) {
					if(item[3] != 0) {
						new_attach.push(item);
					}
				});
				_attach = new_attach;
				if (_attach.length > 0) {
                var attsize;
                // mail_atts = _attach.clone();
                var q = mail.attach[0];
                attrfiles.push('附件:&#10;');
                
                _attach.each(function(s){
                    attsize = s[2];
                    attrfiles.push(["● ", s[0], "(", attsize, ") &#10;"].join(''));
                });
                singleimage.push(["&nbsp;<img src='", MailConst.ALL, "/icon_fujian1.gif' align='absmiddle' /> &nbsp; <a href='javascript:;' hidefocus='true' class='s_filepreview'", ">", q[0]].join(''));
                if (_attach.length > 1) {
                    singleimage.push("&nbsp;&nbsp;...");
                }
                singleimage.push(["</a>(", attsize, ");&nbsp;&nbsp;&nbsp;&nbsp;共", _attach.length, "个附件，"].join(''));
                if(_attach.length > 1){
                    singleimage.push("<a href='download/" + mail.mid + ".4' target = '_blank' >全部下载</a> ");
                    if(G.hasUDiskRights()){
                        html_savetoudisk = " <a href='javascript:;' onclick='mailAttchement.saveToUDisk(\""+mail.mid+"\");return false;'>转存到U盘</a>";
                        singleimage.push(html_savetoudisk);
                    }
                }
                singleimage = ["<span id='single_att' title='", attrfiles.join(''), "'>", singleimage.join(''), " </span>"];
				}
            }
        } catch(e) { }
        
        if (attrfiles.length > 0) {
            pageContent.push('<dd id="atts_notifier">附　件：');
            pageContent.push(singleimage.join(''));
            pageContent.push('</dd>');
        }
        pageContent.push('</dl>');

        // add by alvayang for notifier
        if(is_disp_notifier == 1 && is_disp_notifier_s == 0){
            pageContent.push('<div id="disposition" style="height:25px;background-color:#ffe3b2;border:1px;border-color:#ffb15c;border-style:solid;padding-left:5px;font-size:14px;font-weight:bold;valign:absolute;line-height:25px;font-color:#d15300">');
            pageContent.push('<div id="disposition_desc" style="float:left">' + s_c[0] + '：希望得到您阅读此信的回执,是否发送?</div>');
            pageContent.push('<div id="disposition_controller" style="float:right; padding-right:10px;">');
            pageContent.push('<div style="float:left;margin-left:10px;text-decoration:underline;cursor:pointer" class="reply_notifier">发送</div>');
            pageContent.push('<div style="float:left;margin-left:10px;text-decoration:underline;cursor:pointer" class="cancel_reply_notifier">不发送</div>');
            pageContent.push('</div>');
            pageContent.push('</div>');
        }
        // notifier end

        pageContent.push('<ul id="read_mail_content" class="ulstyle"><p>');
        pageContent.push(((s_c[2] != '') ? s_c[2] : '暂无内容'));
        pageContent.push('</p></ul>');
        
        if (_attach.length > 0) {
            pageContent.push('<div style="border-bottom:1px solid #E6E5E5;">');
            if(_attach.length > 1){
                pageContent.push('<div style="padding:4px 8px;height:18px;width:auto;background-color:#FDFBF5;border-bottom:1px solid #E6E5E5;"><div style="float:left;">附件预览</div><div style="float:left;margin-left:5px;">&nbsp;&nbsp;&nbsp;&nbsp;共 ' + _attach.length + ' 个附件，<a href="download/'  + mail.mid + '.4" target="_blank">全部下载</a>'+html_savetoudisk+'</div><div style="float:right;" class="s_ispreview"> 关闭 <img src="' + MailConst.ALL + '/icon_bottom1.gif" align="absmiddle" /></div></div>');
            }else{
            pageContent.push('<div style="padding:4px 8px;height:18px;width:auto;background-color:#FDFBF5;border-bottom:1px solid #E6E5E5;"><div style="float:left;">附件预览</div><div style="float:right;" class="s_ispreview"> 关闭 <img src="' + MailConst.ALL + '/icon_bottom1.gif" align="absmiddle" /></div></div>');
            }
            pageContent.push('<div id="read_att_pre">' + this.loadAttPreView(_attach, light) + '</div>');
            pageContent.push('</div>');
        }
        
        if (mailList.currentFolder != 2 && mailList.currentFolder != 3 && mailList.currentFolder != 4) {
            //快捷回复
            fastreplyValue = addrName + "," + (receiverName == "" ? "" : receiverName) + (copyName == "" ? "" : copyName);
            fastreplyValue = fastreplyValue.substring(0, fastreplyValue.lastIndexOf(","));
            pageContent.push('<div id="read_mail_replay" class="fast-reply">');
            pageContent.push('<h5 id="replySuccMsg" style="display:none;width:98%;text-align:center;"><img src="' + MailConst.ALL + '/icon_ok.gif" align="absmiddle"/>您已成功回复本邮件！</h5>');
            pageContent.push('<div id="fastReplyDown" class="edit-area">' +
            '<div class="area1"><div class="leftp"><span style="float:left;display:none;">选择发件人：</span><span id="selectXfrom" style="display:none;margin-right:10px;float:left;"></span><span id="selectReplay" style="float:left;"></span></div><div class="rightp s_reply_area"> 关闭 <img src="' +
            MailConst.ALL +
            '/icon_bottom1.gif" align="absmiddle" /></div></div>' +
            '<div class="area2"><div class="leftp"><textarea id="reply_textarea" class="textarea" onblur="mailRead.restoreState();" onfocus="mailRead.changeState();" onkeyup="mailRead.ctrlEnter(event);">快速回复给：' +
            fastreplyValue +
            '</textarea></div><div class="leftp"><a id="reply_button" class="s_reply_button" hidefocus="true" disabled="true" href="javascript:;"><img id="reply_img" src="' +
            MailConst.ALL +
            '/button_revert_grey.jpg" /></a></div></div>' +
            '</div>');
            
            pageContent.push('<div id="fastReplyUp" class="edit-area" style="display:none;">' +
            '<div class="area"><div class="leftp">快速回复</div><div class="rightp s_reply_area"> 打开 <img src="' +
            MailConst.ALL +
            '/icon_top1.gif" align="absmiddle" /></div></div>' +
            '</div>');
            pageContent.push('</div>');
        }
		var _c = pageContent.join('');
        return _c;
    },
	// 读信页面添加选择发件人的选择菜单
	loadSelectXfrom: function() {
		var _sf = $('selectXfrom'), _sc = [UserSohuID], _sc_f = [], _options = [{
			text: UserSohuID,
			exec: function(event) {
				_sf.setAttribute('xfrom', UserSohuID);
			}
		}];
		for(var i in mailPop.PopAccounts) {
			// _sc.push(mailPop.PopAccounts[i]['folder']['name']);
			var _n = mailPop.PopAccounts[i]['folder']['name'];
			_options.push({
				text: _n,
				exec: function(event) {
					_sf.setAttribute('xfrom', _n);
				}
			});
		}
		if(_options.length == 1) return false;
		new Select().init(_sf, _options);
		_sf.show();
		Element.show(_sf.previousSibling);
	},
	// 设置常用回复语
	loadReplyText: function() {
		var _sp = $('selectReplay'), _options = [];
		var self = this;
		this.replayOptions.each(function(item, index) {
			_options.push({
				text: item,
				exec: function(event) {
					if(index == 0) return false;
					self.addReplayValue(item);
				}
			});
		});
		if(_sp) {
			// _select.init(_sp, _options);
			new Select().init(_sp, _options);
		}
	},
	// 从列表缓存中删掉一封会话
	delCinList: function(index, list) {
		this.delMail = list[index];
		return list.slice(0, index).concat(list.slice(index+1));
	},
	
	/*
	getSenderName: function(name, addr) {
		return ((name && name != null) ? name + '&lt;' + addr + '&gt;' : addr);
	},
	*/
	
	// 设置星标
    setStar: function(el) {
        var _star = el.sid ? el.sid : el.getAttribute('sid');
        _star = (parseInt(_star) + 1) % 6;
        var params = {
            id: this.currentMail.rowid,
            method: 2,
            star: _star
        };
        mailStarList._opt_id = _star;
        mail_change_star(params, mailStarList.update_folder_cache);
		
		try {
			// el.src = MailConst.ALL + mailList.multiStar.img[_star];
			mailList.setStarClass(el, mailList.multiStar.star[_star]);
            el.title = mailList.multiStar.title[_star];
			el.setAttribute('sid', _star);
		} catch(e) {}
		try {
			mailList.setStarMailCache(this.currentMail.rowid, _star);
		} catch(e) {}
		try {
			PROFILE.usestar = 1;
		} catch(e) {}
    },
	// 附件的预览
	loadAttPreView: function(attach, light) {
		if(typeof attach != 'object' || attach.length == 0) return '';
    	var c = [];
		c.push('<table cellspacing=0 cellpadding=0 border=0 style="margin:10px;"><tbody>');
    	attach.each(function(item) {
			var att_name = mailSearch.replaceHeighLight([item[0]], light)[0];
			c.push('<tr>');
			var d_url = './download/' + item[4] + '.1';
            var html_saveToUdisk = "";
            if (G.hasUDiskRights()){
                html_saveToUdisk = '<a href="javascript:;" style="margin:0 5px;" onclick="mailAttchement.saveToUDisk(\''+item[4]+'\',false)">转存到U盘</a>';
            }
			var _img_type = ['bmp', 'jpg', 'jpeg', 'gif', 'png', 'ico'],
			v_type = function(str) {
				var f = false;
				_img_type.each(function(item) {
					if(str.include(item) && !f) f = true;
				});
				return f;
			}
			if(item[1].include('image') && v_type(item[1])) {
				var p_url = './download/' + item[4] + '.0';
				var p_url1 = './download/' + item[4] + '.2';
				c.push(['<td style="padding:10px;"><a href="', p_url, '" target="_blank" hidefocus="true"><img src="', p_url1, '" style="width:160px;border:1px solid #E6E5E5;" /></a></td>',
		                '<td style="padding:10px;" valign="top"><div><span>', att_name, '</span>(', item[2], ')</div><div><a style="margin:0 5px;" href="', d_url, '" hidefocus="true">下载</a>'+html_saveToUdisk+'</div></td>'].join(''));
			} else {
				var p_url2 = './download/' + item[4] + '.3';
				var type = this.isKnow(item[0]);
				if (item[1].include('msword') || item[1].include('ms-excel') || item[1].include('pdf')) {
					c.push(['<td style="padding:10px;"><a href="', p_url2, '" target="_blank" hidefocus="true"><img src="', MailConst.ALL, "/type/", type, '.gif" /></a></td>', '<td style="padding:10px;" valign="top"><div><span>', att_name, '</span>(', item[2], ')</div><div><a style="margin:0 5px;" href="', d_url, '" hidefocus="true">下载</a>'+html_saveToUdisk+'&nbsp;<a style="margin:0 5px;" target="_blank" href="', p_url2, '" hidefocus="true">在线预览</a></div></td>'].join(''));
				}
				else {
					c.push(['<td style="padding:10px;"><img src="', MailConst.ALL, "/type/", type, '.gif" /></td>', '<td style="padding:10px;" valign="top"><div><span>', att_name, '</span>(', item[2], ')</div><div><a style="margin:0 5px;" href="', d_url, '" hidefocus="true">下载</a>'+html_saveToUdisk+'</div></td>'].join(''));
				}
			}
			c.push('</tr>');
   		}.bind(this));
		c.push('</tbody></table>');
    	return c.join('');
	},
	// 附件格式的判断
	isKnow: function(type) {
		var k_types = ['txt', 'eml', 'doc', 'avi', 'pdf', 'ppt', 'rar', 'swf', 'wav', 'wma', 'xls', 'xml', 'zip', 'fla', 'mp3'];
		var _r = 'none';
		k_types.each(function(item) {
			if(type.toLowerCase().endsWith(item)) _r = item;
		});
		return _r;
	},
	
	// 回复、转发、快速回复
    replyMail: function(type) {
        var _type = ['fastreply', 'reply', 'replyall', 'forward'];
		if(type == _type[0]) {
			var rpltxt = $('reply_textarea');
			if (rpltxt.value.startsWith("快速回复给：")) {
				_dialog.alert({info: '请输入回复内容！'});
				rpltxt.focus();
				return;
			}
			if(rpltxt.value.strip()==""){
				_dialog.alert({info: '请输入回复内容！'});
				rpltxt.focus();
				return;
			}
		}
        var _currentMail = this.currentMail;
        var rm = new Template(revertMailTemplate);
        var data = {};
        data['email'] = _currentMail.envelope.from[0][1];
        data['name'] = getSenderName(_currentMail.envelope.from[0]);
        data['subject'] = _currentMail.envelope.subject;
        data['content'] = _currentMail.display;
		data['date'] = strfTime(_currentMail.envelope.date_sent*1000);
		var ccs = '';
		_currentMail.envelope.cc.each(function(_item) {
			ccs += ("<span title='" + _item[1] + "'>" +
            	getSenderName(_item) +
              	"</span>, &nbsp;");
		});
		data['cc'] = ccs != '' ? '<b>抄　送:</b> '+ ccs +'<br />' : '';
        var __to = [], __to_all = [], __cc = [], __bcc = [], _sub = '', _content = '';
        __to = format_reply_to(_currentMail);
		__to_all = format_reply_to(_currentMail).concat(format_filter(_currentMail.envelope.to));
        __cc = format_filter(_currentMail.envelope.cc);
        __bcc = format_filter(_currentMail.envelope.bcc);
		
        var _sw = function(str) {
            return _currentMail.envelope.subject.startsWith(str);
        };
        var _fsw = !_sw('回复') && !_sw('答复') && !_sw('Re') && !_sw('re') ? true : false;
		try {
			var _rt = mailCfgClass.getProfileContent().replytoken, _ico = mailCfgClass.getProfileContent().includeoriginal;
		} catch(e) {}
		if (type == _type[3]) {
			_sub = _currentMail.envelope.subject.startsWith('转发') ? _currentMail.envelope.subject : '转发：' + _currentMail.envelope.subject;
		} else {
			if (_rt && _rt != '') {
				if (_fsw) {
					_sub = _rt.replace(/\\/g, '') + ' ' + _currentMail.envelope.subject;
				} else {
					_sub = _currentMail.envelope.subject;
				}
			} else {
				if (_fsw) {
					_sub = '回复: ' + _currentMail.envelope.subject;
				} else {
					_sub = _currentMail.envelope.subject;
				}
			}
		}
        if (_ico == 'manual' && type != _type[3]) {
			 _content = '';
        } else {
            _content = "<br /><br /><br /><div id='addMailSign'><span> </span></div><div id='mailcontent'>" +
            rm.evaluate(data).replace(/id=\"sohu_mail_stationery_name\"/g, "").replace(/id=\"sohu_mail_stationery_content\"/g, "").replace(/id=\"addMailSign\"/g, "").replace(/id=\"imageSign\"/g, "").replace(/id=\"personalSign\"/g, "").replace(/id=\"textSign\"/g, "") +
            "</div>";
        }
		var _atsv = mailCfgClass.getProfileContent().autosave == false ? 0 : 1;
		if (type == _type[0]) {
			mail_send_e.genuuid();
			var _env = {
				original_id: _currentMail.rowid,
				draft_type: 3,
				message_id: _currentMail.envelope.message_id,
				references: _currentMail.envelope.references.concat(_currentMail.envelope.message_id),
				reply_to: _currentMail.envelope.reply_to,
				in_reply_to: [_currentMail.envelope.message_id],
				mail_followup_to: _currentMail.envelope.mail_followup_to,
				save_after_send: mailCfgClass.get_profile_content.autosave == false ? 0 : 1,
				save_to_addressbook: mailCfgClass.get_profile_content.autosavesendmail == false ? 0 : 1,
				thread: _currentMail.thread
			};
			_content = $('reply_textarea').value + '<br /><br /><br />' + _content;
			var params = {
				is_html : true,
				subject : _sub,
				from: UserSohuID,
				to : format_mail(__to),
				cc : format_mail(__cc),
				bcc : format_mail(__bcc),
				content : _content,
				text : writemail._content2text(_content),
				// is_save : _atsv,
				is_send: 1,
				origin : 0,
				env: Object.toJSON(_env),
				securityCode: mail_send_e.UUID,
				sendtime: mail_send_e._sendtime
			};
			try {
				// var _sf = $('selectXfrom').getElementsByTagName('select')[0];
				var _n = $('selectXfrom').getAttribute('xfrom');
				/*
				if(_sf && _sf.options.length > 1) {
					var _xfrom = _sf.options[_sf.selectedIndex].value;
					if(_xfrom != UserSohuID) params.xfrom = _xfrom;
				}
				*/
				if(_n != UserSohuID) params.xfrom = _n;
			} catch(e) {}
			mail_send(params, this.fastReplyCallBack.bind(this), this.fastReplyFailureCallBack.bind(this));
		} else {
			if (type == _type[1]) {
				writemail.to = format_mail(__to);
				writemail.cc = '';
				writemail.bcc = '';
				writemail.draft_type = 2;
			} else if (type == _type[2]) {
				writemail.to = format_mail(__to_all);
				writemail.cc = format_mail(__cc);
				writemail.bcc = format_mail(__bcc);
				writemail.draft_type = 2;
			} else if (type == _type[3]) {
				writemail.to = '';
				writemail.cc = '';
				writemail.bcc = '';
				writemail.draft_type = 1;
			}
			with (writemail) {
				original_id = _currentMail.rowid;
				message_id = _currentMail.envelope.message_id;
				references = _currentMail.envelope.references.concat(_currentMail.envelope.message_id);
				reply_to = _currentMail.envelope.reply_to;
				in_reply_to = [_currentMail.envelope.message_id];
				mail_followup_to = _currentMail.envelope.mail_followup_to;
				subject = _sub;
				content = _content;
				orig_uid = _currentMail.envelope.from[0] ? _currentMail.envelope.from[0][1] : _currentMail.envelope.from_after_1st_unread[0][1];
			};
			composeMail();
			if (type == _type[3]) {
				if (_currentMail.attach.length > 0) {
					var params = {
						mail: _currentMail.rowid
					};
					mail_save_att(params, function(ret){
						if (ret.length > 0) {
							mail_save_att({}, function(_ret){
								var _tmp = [];
								_ret.each(function(_item){
									if (ret.include(_item.id)) {
										_tmp.push(_item);
									}
								});
								mailUploadFile.createInitInfo(_tmp);
								writemail.attDivContent = $("uploadInfoDIV").innerHTML;
							});
						}
					});
				}
			}
		}
    },
    fastReplyCallBack: function(ret) {
        var rpltxt = $('reply_textarea'), rplsucc = $('replySuccMsg'), fpd = $('fastReplyDown');
        if (typeof ret == 'object' && ret.id) {
            rplsucc.show();
            // fpd.hide();
            rpltxt.value = '快速回复给：' + fastreplyValue;
            // rpltxt.className = 'grey';
            var t = setTimeout(function(){
                clearTimeout(t);
                t = null;
                rplsucc.hide();
            }, 5000);
            
        } else {
            _dialog.alert({
                info: '未知错误，请重试！'
            });
        }
    }, 
	fastReplyFailureCallBack: function() {
		_dialog.alert({info: '由于网络原因，您的邮件没有发送成功，请重试！'});
	},
	
	// 点击附件，定位到被下载的位置
	focusPreview: function(){
		DOM.sohuMailMain.scrollTop = Position.cumulativeOffset($('read_att_pre'))[1];
	},
	// 打开、关闭附件区域
	isPreview: function(obj) {
		var _rap = $('read_att_pre');
		var el = obj.className.include('s_ispreview') ? obj : obj.parentNode.className.include('s_ispreview') ? obj.parentNode : obj.parentNode.parentNode.className.include('s_ispreview') ? obj.parentNode.parentNode : null;
		if(_rap.visible()) {
			_rap.hide();
			el && (el.innerHTML = ' 打开 <img src="'+MailConst.ALL+'/icon_top1.gif" align="absmiddle" />');
		} else {
			_rap.show();
			el && (el.innerHTML = ' 关闭 <img src="'+MailConst.ALL+'/icon_bottom1.gif" align="absmiddle" />');
		}
	},
	
	// 显示快捷回复的常用语
	setSelect: function(oSelect,oOptions,iIndex) {
		var _select = document.createElement('select'), self = this;
		_select.onchange = function() {
			self.addReplayValue();
		};
		oSelect.appendChild(_select);
		_select.options.length = oOptions.length;
		for (var i = 0; i < oOptions.length; i++) {
			_select.options[i].text = _select.options[i].value =oOptions[i];
		}
		_select.selectedIndex = iIndex;
	},
	
	addReplayValue: function(value) {
		/*
		var rpltxt = $('reply_textarea'), selt = $('selectReplay').firstChild, replayIndex = selt.selectedIndex;
    	if(replayIndex != 0){
    		rpltxt.value = selt.options[replayIndex].value;
			try {
				rpltxt.addClassName('black');
			} catch(e) {}
    	}
		$('reply_img').src=MailConst.ALL +"/button_revert.jpg";
		*/
		$('reply_textarea').value = value;
		$('reply_img').src=MailConst.ALL +"/button_revert.jpg";
	},
	
	// 打开、关闭快捷回复区域
	isFastReply: function() {
		try {
			var fpu = $('fastReplyUp'), fpd = $('fastReplyDown'), rmr = $('read_mail_replay');
			if (fpd.visible()) {
				fpd.hide();
				fpu.show();
			} else {
				fpd.show();
				fpu.hide();
			}
		} catch(e) {}
	},
	
	// 快速回复获得鼠标焦点时候的状态
    changeState: function() {
        var rpltxt = $('reply_textarea');
        if (rpltxt.value.startsWith('快速回复给：')) {
            rpltxt.value = '';
            try {
                rpltxt.addClassName('black');
            } catch (e) { }
        }
        $('reply_img').src = MailConst.ALL + '/button_revert.jpg';
    },
	
	// 快速回复焦点离开时的状态
    restoreState: function(){
        var rpltxt = $('reply_textarea');
        if (rpltxt.value == "") {
            rpltxt.value = "快速回复给：" + fastreplyValue;
            try {
                rpltxt.removeClassName('black');
            } catch (e) {}
            $('reply_img').src = MailConst.ALL + "/button_revert_grey.jpg";
        }
    },
	
	// Ctrl + Enter的快捷键
	ctrlEnter: function(event) {
		event = event || window.event;
		if(event.ctrlKey && event.keyCode == 13) {
			this.replyMail('fastreply');
		}
	},
	
	// 移动、删除邮件
	mailMove: function(did, method) {
		var self = this;
		var _method = method ? method : 1;
		var confunc = function() {
			var params = {
				src : self.folder,
				dest : did,
				method : _method,
				id : self.currentMail.rowid
			};
			var _cb = arguments[0];
			mail_move(params, function(ret) {
				try {
					var _index = 0;
					self.cacheList.each(function(item, index) {
						if(item.rowid == self.currentMail.rowid) _index = index;
					});
					if(self.folder != -2) self.cacheList = self.delCinList(_index, self.cacheList);
					mailList.clearListCache();
					mailList.refreshListFlag = true;
				} catch(e) {}
				try {
					var _tips = '';
					_tips = self.op_tips['fid_' + did];
					if(did > 5) _tips = self.op_tips['fid_0'];
					if(_method == 3) _tips = self.op_tips['fid_' + _method];
					if(_tips) Tips.show(_tips, 5);
				} catch(e) {}
				if(NEXT_ID) {
					self.getMailRead(NEXT_ID);
				} else if(PREV_ID) {
					self.getMailRead(PREV_ID);
				} else {
					changePanel('mailList', self.folder);
				}
				if(_cb && typeof _cb == 'function') {
					_cb(ret);
				}
			});
		};
		
		// method: 3 --> 垃圾举报
		if(method == 3) {
			var _sender = [];
			_sender.push(this.currentMail.envelope.from[0][1]);
			if(!mailConference.spamMailLayer(_sender, false, function() {
				confunc(function(ret) {
					var _cid = $('content_id');
					if(_cid) {
						_cid.innerHTML = '<dt class="t-txt">举报成功！邮件已提交反垃圾系统数据中心！</dt><div><div> 今天搜狐反垃圾系统共收到<b> '+ ret.spamall +' </b>次举报 </div><div> 共拦截了<b> '+ ret.spammail +' </b>封垃圾邮件 </div><div> 感谢您对搜狐邮箱反垃圾工作的支持！ </div></div><div style="margin-top:20px;text-align:center;"><input class="button6" type="button" value="　关闭窗口　" onclick="_dialog.closeCustom();" /></div>';
					}
				});
			})) return false;
		}
		
		if(did == -1) {
			_dialog.confirm({info: '您确定要彻底删除当前邮件?', click: function(event) {
				confunc();
			}});
			return false;
		}
		confunc();
	},
	
	// 获得可以移入的邮件夹
    getFolderList: function() {
        var l = [];
		var self = this;
        FolderList.each(function(item){
            if (item.folder_id != self.folder && item.folder_id != 2 && item.folder_id != 3 && item.folder_id != 4 && item.folder_id != 5 && item.folder_id != -2 && item.folder_id > -5) {
                l.push({
                    text: item.name,
                    onclick: function(){
						self.mailMove(item.folder_id);
                        return false;
                    }
                });
            }
        });
        return l;
    },
	
	// 将发件人保存到地址簿
	saveAddr: function(el, event, data) {
		var _data = data ? data : this.currentMail;
		var _f = _data.envelope.from[0], _n = _f[0]!='' ? _f[0] : _f[1].split('@')[0], _e = _f[1];
		var _div = document.createElement('div');
		_div.setAttribute('id', 'sign');
		var html = ['<div class="newadd" onclick="Event.stop(event);"><h4>联系人基本信息</h4>',
		           '<ul>',
		 		   '<li>昵　　称：<input type="text" class="input2" value="'+ _n +'" />',
				   '<b> *</b></li>',
				   '<li>邮箱地址：'+ _e +'</li>',
				   '<li style="margin-bottom:10px;">添加成功后，可以到地址簿编辑联系人信息</li>',
			       '<li style="margin-left:60px;"><input value="确　定" type="button"  class="yes" />&nbsp;',
				   '<input value="取　消" type="button" class="yes" /></li>',
				   '</ul></div>'].join('');
		_div.innerHTML = html;
		menu.showMenu(el, DOM.sohuMailMain, _div, '', true, null, event);
		var l = _div.getElementsByTagName('input');
		var _nick = l[0].value;
		var checkData = /<|>|'|;|&|#|"|'/;
            l[1].onclick = function(event) {
                var flag = false;
				_nick = l[0].value;
				var _j = [{
					d: _nick.blank(),
					t: '昵称不能为空'
				}, {
					d: checkData.test(_nick),
					t: '昵称不能包含特殊字符'
				}, {
					d: mailAddressClass._check_length(_nick) > 20,
					t: '昵称的长度英文不能大于20个字符，中文不能大于10个字符'
				}];
                _j.each(function(item){
                    if (item.d && !flag) {
                        _dialog.alert({info: item.t});
                        flag = true;
                    }
                });
                if (flag) return false;
                var in_blacklist = false;
                blackLists.each(function(item){
                    if (item.email == _e) in_blacklist = true;
                });
                var confunc_sends = function(){
					var params = {
						fullname : _nick,
						nickname : _nick,
						personalemail : _e
					};
                    add_d_contact(params, function(ret) {
						if (!ret.status) {
							if (ret.errmsg == 'user is exist!') {
								_dialog.alert({info: '这个用户已经存在！'});
								return;
							} else {
								var _msg = ret.errmsg ? ret.errmsg : (ret.msg ? ret.msg : '系统错误，请稍后重试');
								_dialog.alert({info: _msg});
								return;
							}
						}
						if (mailAddressClass.checkAddrLimit([ret.msg], true)) {
							contactLists.push(ret.msg);
							var adiv = mailAddressClass.createListItem(ret.msg);
							mailAddressClass.mailAddrListDOM.push(adiv);
							mailAddressClass.setRecentItemNick(ret.msg);
						}
						_dialog.alert({info: '<b>联系人添加成功!</b><br /><a href="main#addressList" onclick="changePanel(\'contactList\');_dialog.close();return false;" hidefocus="true">去地址簿查看 >></a><br />该联系人已同时加入您的收信白名单，以后来自该地址的邮件都将进入您的收件箱。'});
						try {
							el.parentNode.removeChild(el);
						} catch(e) {}
					});
					menu.closeMenu();
                };
                if (in_blacklist) {
                    _dialog.confirm({
                        info: '该地址在黑名单中，添加到地址簿会将其从黑名单中删除，是否要继续？',
                        click: function(){
                            confunc_sends();
                            var _black_list = []
                            blackLists.each(function(item){
                                if (item.email != _email) 
                                    _black_list.push(item);
                            });
                            blackLists = _black_list;
                        }
                    });
                    return false;
                }
                confunc_sends();
            };
		l[2].onclick = function(event) {
			menu.closeMenu();
		};
	},
	
	// 拒收
	refuseAddr: function(el, data) {
		var self = this;
		var _data = data ? data : this.currentMail;
		var confunc_refuse = function() {
			var params = {
				id: _data.rowid,
				src : mailList.currentFolder,
				dest : -1,
				method: 1
			};
			var _e = _data.envelope.from[0][1];
			mail_move(params, function(ret) {
				// 清缓存
				try {
					if(mailList.mailListCache['inbox'+mailList.currentFolder]) {
						mailList.mailListCache['inbox'+mailList.currentFolder] = [];
						mailList.refreshListFlag = true;
					}
				} catch(e) {}
				mailCfgClass.setMailCfgRefuse(_e, function() {
					if(NEXT_ID) {
						self.getMailRead(NEXT_ID);
					} else if(PREV_ID) {
						self.getMailRead(PREV_ID);
					} else {
						changePanel('mailList', self.folder);
					}
					try {
						el.parentNode.removeChild(el);
					} catch(e) {}
				});
			});
		};
		_dialog.confirm({info: '您确定要拒收吗？', click: function() {
			confunc_refuse();
		}});
	},
	
	// 保存所有收件人的地址
	saveAllAddr: function(el, event, data) {
		var _data = data ? data : this.currentMail;
		var _div = document.createElement('div');
		_div.setAttribute('id', 'sign');
		var _html = [], cm = [], _cl = [], _cl_e = [];
		// 保存所有联系人包括抄送中的
		cm = _data.envelope.to.concat(_data.envelope.cc);
		cm.each(function(item, index) {
			/*
			if(item[1].include(UserSohuID)) {
				_html.push('<tr><td></td><td></td><td>'+ item[1] +'</td><td>我</td></tr>');
			} else
			*/ 
			// 联系人地址的排重
			if(_cl_e.include(item[1])) return false;
			_cl.push(item);
			_cl_e.push(item[1]);
			if(!IsEmail(item[1], false)) return false;
			if(mailIsContact(item[1])) {
				_html.push('<tr><td></td><td></td><td>'+ item[1] +'</td><td>已添加</td></tr>');
			} else if(mailIsBlack(item[1])) {
				_html.push('<tr><td></td><td></td><td>'+ item[1] +'</td><td>黑名单</td></tr>');
			} else {
				_html.push('<tr><td><input type="checkbox" value="'+ item[1] +'" name="'+ item[0] +'" /></td><td></td><td>'+ item[1] +'</td><td>可添加</td></tr>');
			}
		});
		var html = ['<div class="newadd" style="margin:10px 10px">',
				    '<div><table cellspacing="0" cellpadding="0" border="0" class="list"><tbody>',
				    '<tr><th style="width:6%;"><input type="checkbox" value="" /></th><th style="width:12%;">全选</th><th style="width:66%;">邮件地址</th><th style="width:16%;">状态</th></tr>',
					_html.join(''),
					'</tbody></table></div>',
					'<div style="margin:6px 0px;">说明：系统将自动将@前面的内容作为联系人昵称。</div>',
					'<div style="text-align:center;">',
					'<input type="button" value="确　定" class="yes" />　',
					'<input type="button" value="取　消" class="yes" />',
					'</div>',
					'</div>'].join('');
		_div.innerHTML = html;
		var _flag = false;
		Event.observe(_div, 'mousedown', function(event) {
			_flag = true;
		});
		var self = this;
		this.menu = new Menu();
		this.menu['_closeMenu'] = function() {
			if (_flag) {
				_flag = false;
				return false;
			}
			try {
				Event.stopObserving(_div, 'mousedown');
			} catch(e) {}
			try {
				Event.stopObserving(DOM.sohuMailMain, 'click', self.menu['_closeMenu']);
			} catch(e) {}
			self.menu.closeMenu();
			self.menu = null;
		};
		Event.observe(DOM.sohuMailMain, 'click', self.menu['_closeMenu']);
		this.menu.showMenu(el, DOM.sohuMailMain, _div, '', true, true, event);
		var _t_l = $A(_div.getElementsByTagName('table')[0].getElementsByTagName('input')), _t_list = _t_l.slice(1);
		var _t_o = $A(_div.getElementsByTagName('input')).slice(-2);
		_t_l[0].onclick = function(event) {
			if(this.checked) {
				_t_list.each(function(item) {
					item.checked = true;
				});
			} else {
				_t_list.each(function(item) {
					item.checked = false;
				});
			}
		};
		_t_o[0].onclick = function(event) {
			var _mails = [];
			$A(_div.getElementsByTagName('input')).each(function(item) {
				if(item.checked && IsEmail(item.value, false)) {
					_mails.push(item.value);
				}
			});
			if(_mails.length == 0) {
				_dialog.alert({info: '请选择需要添加的联系人'});
				return false;
			}
			var _params = {
				emails: _mails.join(',')
			};
			fast_add_contact(_params, function(ret) {
				if (!ret.status) {
					_dialog.alert({info: ret.msg});
					return false;
				}
				var _save_list = ret.msg;
				if(mailAddressClass.checkAddrLimit(_save_list, true)) {
					contactLists = contactLists.concat(_save_list);
					_save_list.each(function(item) {
						var adiv = mailAddressClass.createListItem(item);
						mailAddressClass.mailAddrListDOM.push(adiv);
						mailAddressClass.setRecentItemNick(item);
					});
				}
				var _p = [], _s = [], _s_id = [];
				_save_list.each(function(item) {
					_p.push('<li style="margin-left:20px;">' + item.email + ' 添加成功</li>');
					_s_id.push(item.id);
				});
				_s.push(' 联系组名称：');
				_s.push('<select>');
				_s.push('<option value=""> 请选择 </option>');
				_s.push('<option value="-1"> 新建通讯组 ...  </option>');
				contactCates.each(function(item) {
					if(item.id <= 0) return;
					var len = item.contactid == '' ? 0 : item.contactid.split(',').length;
					_s.push('<option value="'+item.id+'">'+item.name+'('+len+')</option>');
				});
				_s.push('</select>');
				var _html = ['<div class="newadd" style="margin:10px 10px">',
							 '<h4 >添加联系人成功!</h4><ul>',
							 _p.join(''),
							 '<li style="margin-top:10px;"><input type="checkbox" name="" value="" /> 将以上联系人添加到通讯组中。</li>',
							 '<li id="groupel" style="margin-top:10px;display:none">',
							 _s.join(''),
							 '</li>',
							 '<li style="margin-top:40px;margin-left:100px;margin-right:60px;" ><input type="button" name="Submit" value="关闭本页" /></li></ul></div>'].join('');
				_div.innerHTML = _html;
				var _l = _div.getElementsByTagName('input');
				_l[0].onclick = function() {
					(this.checked ? Element.show : Element.hide)(this.parentNode.nextSibling);
				};
				_l[1].onclick = function() {
					_flag = false;
					self.menu['_closeMenu']();
				};
				var _s_el = _div.getElementsByTagName('select')[0];
				try {
					_s_el.onclick = function(event) {
						Event.stop(event);
						return false;
					};
				} catch(e) {}
				try {
					_s_el.onchange = function(event) {
						try {
							_flag = false;
							self.menu['_closeMenu']();
							hiddenAllPanel();
							DOM.addressGroupList.show();
						} catch(e) {}
						var _value = this.getElementsByTagName('option')[this.selectedIndex].value;
						try {
							_value != '' && (_value == '-1' ? mailAddressClass.createGroup(true, _s_id) : (function() {
								mailAddressClass.addsGroup(_value, _s_id);
								mailAddressClass.initGroup(_value, true);
							})());
						} catch(e) {}
						return false;
					};
				} catch(e) {}
			});
		};
		_t_o[1].onclick = function(event) {
			_flag = false;
			self.menu['_closeMenu']();
		};
	},
	
    reply_notifier : function(arg, view){
                         var _vis = view == 1 ? true : false;
                         if(_vis){
                             try{
                                 var param = {
                                     'disp_flag' : 1,
                                     'disp_id' : this.currentCid
                                 };
                                 mail_send(param, this.clear_notifier_succ.bind(this), this.clear_with_error.bind(this));
                             }catch(e){ }
                         }else{
                             this.clear_notifier();
                         }
                     },
    clear_with_error : function(){
        //$('disposition').style.display = 'none';
                           $('disposition_desc').innerHTML = "出错了,请稍后尝试";
                           setTimeout(this.clear_notifier, 1200);
    },
    clear_notifier_succ : function(ret){
                           if(ret.is_success){
                               try{
                                   delete this.readMailCache['mail_' + this.currentCid];
                               }catch(e){}
                               // this.currentMail.envelope.userhdrs['Disposition-Notification-Sent'] = 1;
                               $('disposition_desc').innerHTML = "回复成功";
                           }else{
                           $('disposition_desc').innerHTML = "出错了,请稍后尝试";
                           }
                           setTimeout(this.clear_notifier, 1200);
                      },
    clear_notifier: function(){
                        $('disposition').style.display = 'none';
                    },
	
	// 打印邮件
    mailPrint: function() {
		var _domain = isDomain ? localDomain : undefined;
        var _d = _domain ? 'document.domain="' + _domain + '";' : '';
        var _url = 'javascript:document.open();' + _d + 'document.write("<html><head></head><body></body></html>");document.close();';
        var Doc = window.open(_url);
        function _print(content) {
            if (typeof content == 'string') {
                Doc.document.body.innerHTML = content;
            } else {
                Doc.document.body.appendChild(content);
            }
            try {
                function $Doc(id){
                    if (typeof id == 'string') 
                        return Doc.document.getElementById(id);
                    return id;
                }
                function _remove(d){
                    d.parentNode.removeChild(d);
                    d = null;
                }
                var ref = $Doc('refuse.current.sender'), sva = $Doc('rd_add_contact_multi'), sv = $Doc('rd_add_contact');
                if (ref) 
                    _remove(ref);
                if (sva) 
                    _remove(sva);
                if (sv) 
                    _remove(sv);
            } catch (e) {}
            var _t = setTimeout(function(){
                clearTimeout(_t);
                _t = null;
				try {
					if(Doc) Doc.print();
				} catch(e) {}
            }, 1000);
        }
        var _r_t = $('read_title_content'), _r_c = $('read_mail_content');
        if (_r_t && _r_c) {
            var _c = ['<div style="font-size:10pt;">', _r_t.innerHTML, '</div><div style="font-size:10pt;">', _r_c.innerHTML, '</div>'].join('');
            if (Prototype.Browser.Gecko) {
                Doc.onload = function(){
                    _print(_c);
                };
            } else {
                var _t = setTimeout(function(){
                    clearTimeout(_t);
                    _t = null;
                    _print(_c);
                }, 200);
            }
        }
    },
	// 查看邮件的源文件
	viewMailSource: function() {
		var action = 'download/' + this.currentMail.mid + '.0';
		window.open(action);
	},
	// 下载邮件
	downloadMailSource: function() {
		var action = 'download/' + this.currentMail.mid + '.1';
		window.open(action);
	}
};
var mailRead = new MailRead();
